References in c++

Variables are created by:

Definition

Reference is an alias or another name for any given variable.
The way we create an alias is:

	#include<iostream>
	int main()
	{
	int a=5;
	int & b=a;  //here b is an alias of a, now we can access the variable a by two methods, a or b.
	std::cout<<a<<'\t'<<b;
	//(int &b, int & b , int& b - all are same)	
	}

Behind the scenes references uses pointers, but we don't need to go to that level.

Advantages/usage/properties of References

  1. References are majorly used when we are passing large amount of data in a function, when we pass data inside a function we generally copy that data to parameter variables. Have a look below the use of references:
	#include<iostream>
	int add(int &a, int &b)
	{
	int c=a+b;
	return c;
	}
	
	int main()
	{
	int x=50;
	int y=40;
        std::cout<<add(x,y);     // in this way the data 50 and 40 is not copied in any variable, and it saves memory, it is useful when passing billions of data points in a function or passing a vector. It helps in saving memory.
        return 0;
	}
  1. Like pointers any changes made to alias does not remains inside the function only, and changes will reflect outside the function as well. code:
    	#include<iostream>
    	void increment(int &a)
    	{
    	a++;
    	}
    	int main()
    	{
    	int x=5;
    	increment(x);
    	std::cout<<x; //it will print 6 
    	return 0;
    	}
    
    
  2. Location we set to alias/reference is permanent, once we set an alias, we can not make it alias to something else.
    	int a=3;
    	int c=30;
    	int &b=a;
    	b=c; // this statement will store value of c in b which points to address of a, so a=30=b=c
    	return 0;
    
  3. Alias and original variable has same address and it can be checked by following code:
     	#include<iostream>
    	int main()
    	{
    	int a=5;
    	int &b=a;
    	std::cout<<&a<<'\t'<<&b;
    	return 0;
    	}